package com.mzkj.wanjulaile.mobile.api.modules.order.service;

import com.mzkj.common.utils.JedisUtils;
import com.mzkj.wanjulaile.mobile.api.common.utils.RedisUtil;
import com.mzkj.wanjulaile.mobile.api.modules.order.constant.Constant;
import com.mzkj.wanjulaile.mobile.api.modules.order.entity.DSHOrder;
import com.mzkj.wanjulaile.mobile.api.modules.order.entity.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ianly on 16/12/13.
 */
@Service("delayService")
public class DelayService {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    private boolean start ;
    private OnDelayedListener listener;
    private DelayQueue<DSHOrder> delayQueue = new DelayQueue<DSHOrder>();
    private int dshTimeOut;
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    @Autowired
    private OrderService orderService;

    public static interface OnDelayedListener{
        public void onDelayedArrived(DSHOrder order);
    }

    public DelayService(){
        this.start(new OnDelayedListener() {
            @Override
            public void onDelayedArrived(final DSHOrder order) {
                executorService.execute(new Runnable(){
                    public void run(){
                        String orderId = order.getOrderId();
                        //查库判断是否需要自动取消订单
                        Order order1 = orderService.get(orderId);
                        // 未支付 则取消
                        if (null != order1 && order1.getPayStatus().equals(Constant.PAY_STATUS_NOT_PAID_) && !order1.getStatus().equals(Constant.ORDER_CANCEL)){
                            order1.setStatus(Constant.ORDER_CANCEL);
                            orderService.updateStatus(order1);
                            logger.info("超时自动取消，onDelayedArrived():"+orderId);
                            //从redis删除
                            RedisUtil.remove(Constant.RedisKey_DSHORDER_PREFIX+orderId);
                            logger.info("超时自动取消，删除redis："+orderId);
                        }
                    }
                });
            }
        });
    }


    public void start(OnDelayedListener listener){
        if(start){
            return;
        }
        logger.info("DelayService 启动");
        start = true;
        this.listener = listener;
        new Thread(new Runnable(){
            public void run(){
                try{
                    while(true){
                        DSHOrder order = delayQueue.take();
                        if(DelayService.this.listener != null){
                            DelayService.this.listener.onDelayedArrived(order);
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void add(DSHOrder order){
        delayQueue.put(order);
    }

    public boolean remove(DSHOrder order){
        return delayQueue.remove(order);
    }

    public void add(String orderId){
        delayQueue.put(new DSHOrder(orderId, dshTimeOut));
    }

    public void remove(String orderId){
        DSHOrder[] array = delayQueue.toArray(new DSHOrder[]{});
        if(array == null || array.length <= 0){
            return;
        }
        DSHOrder target = null;
        for(DSHOrder order : array){
            if(order.getOrderId() == orderId){
                target = order;
                break;
            }
        }
        if(target != null){
            delayQueue.remove(target);
        }
    }
}
